package com.wn.purchaeReturn.poitool;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;

/**
 * @Author: Tantan
 * @Date: 2022-04-17-11:07
 * @Description:
 */
public class MyExcelExportUtil {

    /**
     * Excel文件导出,导出的文件名默认为:headTitle+当前系统时间
     * @param listData 要导出的list数据
     * @param pojoClass 定义excel属性信息
     * @param headTitle Excel文件头信息
     * @param sheetName Excel文件sheet名称
     * @param response
     */
    public static void exportExcel(Collection<?> listData, /*传入表头不规则信息对象(如供应商信息), 传入模板信息号*/ Class<?> pojoClass, String headTitle, String sheetName, HttpServletResponse response) {
        int i = 1;
        ExportParams params = new ExportParams(headTitle, sheetName);
        params.setHeight((short) 8);
        params.setStyle(ExportExcelUtilStyle.class);
        try {
            Workbook workbook = ExcelExportUtil.exportExcel(params, pojoClass, listData);

            /**
             * 不同的模板可以传入不同的参数值来判断
             * if(id = 1){
             *     供应商模板；
             * }
             * if(id = 2){
             *     采购单模板；
             * }
             */
            if (i == 1){
                //标题下的模板
                workbook.getSheet(sheetName).shiftRows(1, 6, 6);
                workbook.getSheet(sheetName).getRow(1).createCell(2).setCellValue("供应商：");
                //给对应模板后面的格子set值，...setCellValue(供应商.getName())
                workbook.getSheet(sheetName).getRow(1).createCell(4).setCellValue("打印日期：");
                workbook.getSheet(sheetName).getRow(2).createCell(2).setCellValue("采购单号：");
                workbook.getSheet(sheetName).getRow(2).createCell(4).setCellValue("来源单号：");
    //                workbook.getSheet(sheetName).getRow(3).createCell(2).setCellValue("收货地址：");
    //                workbook.getSheet(sheetName).getRow(3).createCell(4).setCellValue("收货人：");
    //                workbook.getSheet(sheetName).getRow(5).createCell(1).setCellValue("收货人电话：");
            }


            String fileName = headTitle + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            fileName = URLEncoder.encode(fileName, "UTF8");
            response.setContentType("application/vnd.ms-excel; chartset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+fileName+".xls");
            ServletOutputStream out=response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
